package fun.ticsmyc.rpc.server.transport.netty.codec;

import fun.ticsmyc.rpc.common.entity.RpcRequest;
import fun.ticsmyc.rpc.common.enumeration.RpcError;
import fun.ticsmyc.rpc.common.exception.RpcException;
import fun.ticsmyc.rpc.common.serializer.Serializer;
import fun.ticsmyc.rpc.common.serializer.Serializers;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author Ticsmyc
 * @date 2020-10-26 10:41
 */
public class RequestDecoder extends ReplayingDecoder<Void> {

    private final int MAGIC_NUMBER = 0xCAFEBABE;
    private final byte CURRENT_PROTOCOL_VERSION = 1;
    private static final Logger logger = LoggerFactory.getLogger(RequestDecoder.class);

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out){
        //魔数
        int magicNumber = in.readInt();
        if(magicNumber != MAGIC_NUMBER){
            logger.error("不识别的协议包,{}",magicNumber);
            throw new RpcException(RpcError.UNKNOW_PROTOCOL);
        }

        //协议版本
        byte protocolVersion = in.readByte();
        if(protocolVersion > CURRENT_PROTOCOL_VERSION){
            logger.error("不能解析的协议版本:{}",protocolVersion);
            throw new RpcException(RpcError.UNKNOW_PROTOCOL);
        }

        //序列化器
        byte serializerCode = in.readByte();
        Serializer serializer = Serializers.getSerializerByCode(serializerCode);
        if(serializer == null){
            logger.error("不能识别的序列化器,{}",serializerCode);
            throw new RpcException(RpcError.UNKNOWN_SERIALIZER);
        }
        //数据包长度和数据包
        int length = in.readInt();
        byte[] bytes = new byte[length];
        in.readBytes(bytes);
        Object deserialize = serializer.deserialize(bytes, RpcRequest.class);

        out.add(deserialize);
        logger.debug("收到客户端请求,{}",ctx.channel().remoteAddress());
    }
}
